import React, { useState } from 'react';
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Button,
  Box,
} from '@mui/material';
import DirectorySelect from './DirectorySelect';

export default function NewDownloadDialog({ open, onClose, onDownload }) {
  const [urls, setUrls] = useState('');
  const [directory, setDirectory] = useState('');

  const handleSubmit = () => {
    // 分割多行URL
    const urlList = urls.split('\n').filter(url => url.trim());
    
    // 对每个URL创建下载任务
    urlList.forEach(url => {
      onDownload({
        url: url.trim(),
        directory
      });
    });

    // 重置表单并关闭对话框
    setUrls('');
    setDirectory('');
    onClose();
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="sm"
      fullWidth
    >
      <DialogTitle>新建下载任务</DialogTitle>
      <DialogContent>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, mt: 2 }}>
          <TextField
            label="下载地址"
            multiline
            rows={4}
            value={urls}
            onChange={(e) => setUrls(e.target.value)}
            placeholder="支持多个URL地址，每行一个"
            fullWidth
          />
          <DirectorySelect
            value={directory}
            onChange={(value) => setDirectory(value)}
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>取消</Button>
        <Button
          onClick={handleSubmit}
          variant="contained"
          disabled={!urls.trim() || !directory}
        >
          确定
        </Button>
      </DialogActions>
    </Dialog>
  );
}